<?php

namespace Modules\Groupon\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;

class GrouponRecord extends Model
{
    protected $guarded = [];
    protected $table = 'groupon_records';

    static public $resourceName = '开团记录';

    protected $appends = ['union_status', 'union_status_text'];

    public function getUnionStatusAttribute()
    {
        $map = [
            1 => 'working',
            2 => 'completed',
            3 => 'failed'
        ];

        return @v($map[$this->status], 'unknow');
    }

    public function getUnionStatusTextAttribute()
    {
        $map = [
            'unknow' => '未知状态',
            'pay_pending' => '待付款',
            'working' => '进行中',
            'completed' => '已完成',
            'failed' => '拼团失败'
        ];

        return @v($map[$this->union_status], '未知状态');
    }

    public function members()
    {
    	return $this->hasMany('Modules\Groupon\Entities\GrouponMember');
    }

    public function orders()
    {
        return $this->belongsToMany('\Modules\Order\Entities\ProductOrder', 'groupon_members', 'groupon_record_id', 'order_id');
    }

    public function groupon()
    {
        return $this->belongsTo('\Modules\Groupon\Entities\Groupon');
    }

    public function product()
    {
        return $this->belongsTo('\Modules\Product\Entities\Product');
    }

    public function leader()
    {
    	return $this->hasOne('Modules\Groupon\Entities\GrouponMember')->where('is_leader', 1);
    }

    public function scopeStatus($query, $status)
    {
    	$map = [
            'paid_pending' => [
                'groupon_records.status' => 0,
            ],
            'working' => [
                'groupon_records.status' => 1,
            ],
            'completed' => [
                'groupon_records.status' => 2,
            ],
            'failed' => [
                'groupon_records.status' => 3
            ]
        ];

        return $query->where($map[$status]);
    }

    static public function beforeGetList($options)
    {
        if (isset($options['status']) && $options['status'] != 'all')
            $options['scopes']['status'] = $options['status'];

        return $options;
    }

    static public function createWith($order, $groupon)
    {
    	$endAt = date('Y-m-d H:i:s', strtotime('+' . $groupon->timeout . ' minutes'));
    	$item = GrouponRecord::create([
    		'groupon_id' => $groupon->id,
            'product_id' => $groupon->product_id,
    		'user_id' => $order->user_id,
    		'need_member' => $groupon->need_member,
    		'end_at' => $endAt,
    		'status' => 0
    	]);

    	$item->members()->create([
    		'uuid' => uniqid(),
    		'user_id' => $order->user_id,
    		'is_leader' => 1,
    		'order_id' => $order->id,
            'status' => 0
    	]);

    	return $item;
    }

    public function addMember($user, $order)
    {
        $this->members()->create([
            'uuid' => uniqid(),
            'user_id' => $user->id,
            'is_leader' => 0,
            'order_id' => $order->id,
            'status' => 0
        ]);

        if ($this->members()->count() >= $this->need_member) {
            $this->complete();
        }
    }

    public function complete()
    {
        $this->update([
            'status' => 2
        ]);

        foreach ($this->orders as $order) {
            $order->update([
                'is_hidden' => 0
            ]);
        }
    }

    public function closeByTimeout()
    {
        $this->close(0);
    }

    public function close($type, $reason = NULL)
    {
        // 关闭订单
        foreach ($this->members as $member) {
            $member->order->closeByGrouponTimeout();
        }

        $this->closed_at = now();
        $this->closed_by = $type;
        $this->status = 3;
        $this->save();
    }

    public function isCanJoin($user)
    {
        return ($this->union_status === 'working' && !$this->members()->paid()->where('id', $user->id)->first());
    }

    public function orderPaid($order)
    {
        $member = $this->members()->whereHas('order', function ($q) use ($order) {
            return $q->where('id', $order->id);
        })->first();

        $member->update([
            'status' => 1
        ]);

        // 设为开团状态
        if ($this->status === 0)
            $this->update([
                'status' => 1
            ]);
    }
}
